package com.ysd.lis.service.qc.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.inti.IntInstrResultNoChannel;
import com.ysd.lis.entity.lab.LabRptGroup;
import com.ysd.lis.entity.qc.QcMaterial;
import com.ysd.lis.entity.qc.QcMaterialItem;
import com.ysd.lis.entity.qc.QcMaterialItemResult;
import com.ysd.lis.entity.qc.QcMaterialItemTarget;
import com.ysd.lis.mapper.qc.QcMaterialItemResultMapper;
import com.ysd.lis.mapper.qc.QcMaterialItemTargetMapper;
import com.ysd.lis.mapper.qc.QcMaterialMapper;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.service.qc.QcMaterialItemResultService;
import com.ysd.lis.service.qc.QcMaterialItemTargetService;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2021-10-08
 */
@Service
@Slf4j
public class QcMaterialItemTargetServiceImpl extends ServiceImpl<QcMaterialItemTargetMapper, QcMaterialItemTarget> implements QcMaterialItemTargetService {

    @Autowired
    QcMaterialItemTargetMapper qcMaterialItemTargetMapper;
    @Autowired
    QcMaterialItemResultMapper qcMaterialItemResultMapper;
    @Autowired
    QcMaterialItemResultService qcMaterialItemResultService;
    @Autowired
    QcMaterialMapper qcMaterialMapper;



    @Override
    public Result findMaterialTargetList(CommonPageDto pageParam) {
        MPJLambdaWrapper<QcMaterialItemTarget> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(QcMaterialItemTarget.class)

                .eq(QcMaterialItemTarget::getMaterialItemId,pageParam.getPid())
                .eq(QcMaterialItemTarget::getDelFlag,0)
                .orderByAsc(QcMaterialItemTarget::getSeq);
        List<QcMaterialItemTarget> targetList = qcMaterialItemTargetMapper.selectList(queryWrapper);

        return Result.succ(1, "查询成功", targetList);
    }

    @Override
    public Result saveOrUpdateMaterialTarget(QcMaterialItem item) {
        List<QcMaterialItemTarget> materialTargetList = item.getMaterialTargetList();
        List<QcMaterialItemTarget> updateTargetList = materialTargetList.stream().filter(ta -> StringUtils.isNotBlank(ta.getId())).collect(Collectors.toList());
        List<QcMaterialItemTarget> addTargetList = materialTargetList.stream().filter(ta -> StringUtils.isBlank(ta.getId())).collect(Collectors.toList());
        boolean b = this.saveOrUpdateBatch(materialTargetList);
        String jsJgFlag = item.getJsJgFlag();
        if(ToolsUtils.isNotEmpty(jsJgFlag)&&jsJgFlag.equals("1")){
            if(materialTargetList.size()>0){
                for(QcMaterialItemTarget qcMaterialItemTarget : materialTargetList){
                    //靶值的启用日期
                    Timestamp enableDate = qcMaterialItemTarget.getEnableDate();
                    Timestamp stopDate = qcMaterialItemTarget.getStopDate();
                    //循环质控靶值，查出此阶段内有效期内质控物的结果
                    MPJLambdaWrapper<QcMaterialItemResult> lambdaQueryWrapper2 = new MPJLambdaWrapper<>();
                    lambdaQueryWrapper2.selectAll(QcMaterialItemResult.class)
                            .innerJoin(QcMaterial.class,"rpt", p->p.eq(QcMaterial::getId,QcMaterialItemResult::getMaterialId)
                                    .eq(QcMaterial::getDelFlag,0)
                                    .le(QcMaterial::getEnableDate, new Timestamp(new Date().getTime()))
                                    .ge(QcMaterial::getValidDate, new Timestamp(new Date().getTime()))
                                    .and(wrapper -> wrapper.isNull(QcMaterial::getStopDate).or().ge(QcMaterial::getStopDate, new Timestamp(new Date().getTime()))))
                            .eq(QcMaterialItemResult::getMaterialId,qcMaterialItemTarget.getMaterialId())
                            .eq(QcMaterialItemResult::getMaterialItemId,qcMaterialItemTarget.getMaterialItemId())
                            .ge(QcMaterialItemResult::getQcDate,enableDate);
                    if(ToolsUtils.isNotEmpty(stopDate)){
                        lambdaQueryWrapper2.le(QcMaterialItemResult::getQcDate,stopDate);
                    }
                    List<QcMaterialItemResult> resultList = qcMaterialItemResultMapper.selectList(lambdaQueryWrapper2);
                    if(ToolsUtils.isNotEmpty(resultList)){
                        for (QcMaterialItemResult qcResult : resultList) {
                            Double sd = qcMaterialItemTarget.getSd();
                            Double mean = qcMaterialItemTarget.getMean();
                            qcResult.setMean(mean);
                            qcResult.setSd(sd);
                            qcResult.setMaterialTargetId(qcMaterialItemTarget.getId());

                            if(null != sd && null != mean){
                                qcResult.setZ(sd==0?0:(qcResult.getNumResult() - mean) / sd);
                            }
                        }
                        qcMaterialItemResultService.saveOrUpdateBatch(resultList);
                        QcMaterial material = qcMaterialMapper.selectById(qcMaterialItemTarget.getMaterialId());
                        qcMaterialItemResultService.QcInstrItemRuleUpdateAsync(qcMaterialItemTarget.getMaterialItemId(),qcMaterialItemTarget.getQcItemId(),qcMaterialItemTarget.getInstrId(),material.getEnableDate(),material.getValidDate());
                    }
                }
            }
        }
        if(b){
            return Result.succ(1, "成功", null);
        }else {
            return Result.fail(400,"失败","");
        }

    }

    @Override
    public Result batchDeleteMaterialTargetList(QcMaterialItem dto) {
        List<QcMaterialItemTarget> targetList = dto.getMaterialTargetList();
        List<String> ids = targetList.stream().map(QcMaterialItemTarget::getId).collect(Collectors.toList());
        boolean b = this.removeByIds(ids);
        if(b){
            return Result.succ(1, "删除成功", null);
        }else {
            return Result.fail(400,"删除失败","");
        }
    }
}
